package org.epidroid.epidroid.androsoul.ui.contactlist;

import java.util.ArrayList;
import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.contacts.ContactGroup;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;

/**
 * Custom adapter that handles the list of groups when changing a contact's
 * groups or adding a new contact
 * 
 */
public class CheckListAdapter extends ArrayAdapter<ContactGroup> implements
		OnClickListener {

	private List<ContactGroup> _items;
	private Context _context;
	private ArrayList<String> _selectedItems = null;

	public CheckListAdapter(Context context, int textViewResourceId,
			List<ContactGroup> dataItems, ArrayList<ContactGroup> init) {
		super(context, textViewResourceId, dataItems);
		this._context = context;
		this._items = dataItems;

		_selectedItems = new ArrayList<String>();

		if (null != init) {
			for (ContactGroup e : init) {
				_selectedItems.add(e.getName());
			}
		}

		// If no item selected, automatically select
		// the first one
		if (_selectedItems.isEmpty()) {
			String name = _items.get(0).getName();
			_selectedItems.add(name);
		}
	}

	public List<ContactGroup> getItems() {
		return _items;
	}

	public ArrayList<String> getSelectedItems() {
		return _selectedItems;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.androsoul_list_item_checkbox, null);
		}
		ContactGroup c = this._items.get(position);

		CheckBox bCheck = (CheckBox) v
				.findViewById(R.id.list_item_checkbox_checkbox);
		bCheck.setText(c.getName());
		bCheck.setTag(c.getName());

		bCheck.setChecked(this._selectedItems.contains(c.getName()));

		bCheck.setOnClickListener(this);

		return (v);
	}

	@Override
	public void onClick(View v) {
		CheckBox cBox = (CheckBox) v;
		String itemText = (String) cBox.getTag();

		if (cBox.isChecked()) {
			if (!this._selectedItems.contains(itemText))
				this._selectedItems.add(itemText);
		} else {
			if (this._selectedItems.contains(itemText))
				this._selectedItems.remove(itemText);
		}
	}

	public void ClearSelections() {
		this._selectedItems.clear();
	}

}
